<?php
include_once 'kliment/db/mySQL/DBTableAbstract.class.php';
include_once 'kliment/utils/StringTool.class.php';
	
class User extends DBTableAbstract {
	const SESSION_KEY_USER_ID = 'user_id';
	const LOGIN = 'login';
	const PASSWORD = 'password';
	private $TABLE_MAIN = 'user"';
	private $_current_user_id;
	private $_status;
	
	function __construct($table_name = '') {
		if ($table_name != '')
			$this->TABLE_MAIN = $table_name;
		
		$user_id = @$this->_session_user_id();
		if (isset($user_id) && $user_id > 0) {
			$this->_current_user_id = $user_id;
		}
	}
	
	public function validateLogin($login) {
		$login = StringTool::escape($login);
		return parent::validateName($login, self::LOGIN, $this->TABLE_MAIN);
	}
	
	public function add($login, $password, $additional_data) {
		$login = StringTool::escape($login);
		$password = StringTool::escape($password);
		
		if ($this->validateLogin($login)) {
			$info = StringTool::cleanRequestVar($additional_data);
			
			$info[self::LOGIN] = $login;
			$info[self::PASSWORD] = md5($password);
			
			return parent::insertRow($this->TABLE_MAIN, $info);
		}
		return false;
	}
	
	public function login($login, $password) {
		$login = StringTool::escape($login);
		$password = StringTool::escape($password);
		
		$password = md5($password);
		
		$sql = "SELECT * FROM `$this->TABLE_MAIN` 
				WHERE `".self::LOGIN."` = '".$login."' AND `".self::PASSWORD."` = '".$password."'
				LIMIT 1";
		$info = parent::singleQuery($sql);
		
		if ($info[self::ID]) {
			$this->_session_user_id($info[self::ID]);
			$this->_current_user_id = $info[self::ID];
			return $info;
		}
		return false;
	}
	
	public function getUserInfo($id) {
		$id = StringTool::escape($id);
		$info = parent::getRowBy($id, self::ID, $this->TABLE_MAIN);
		return $info;
	}
	
	public function getCurrentUserID() {
		return $this->_current_user_id;
	}
	
	public function logout() {
		$this->_session_user_id(0);
		$this->_current_user_id = 0;
	}
	
	public function edit($id, $info) {
		if ($id == $this->_current_user_id) {
			$id = StringTool::escape($id);
			$info = StringTool::escape($info);
			unset($info[self::LOGIN]);
			unset($info[self::ID]);
			return parent::updateRowBy($id, self::ID, $this->TABLE_MAIN, $info);
		}
		return false;
	}
	
	public function getList($limit = "") {
		$sql = "SELECT * FROM `$this->TABLE_MAIN` 
				ORDER BY `".self::LOGIN."` ASC
				$limit";
		return parent::listQuery($sql);
	}
	
	private function _session_user_id($id = null) {
		if ($id !== null)
			$_SESSION[self::SESSION_KEY_USER_ID] = $id;
		return @$_SESSION[self::SESSION_KEY_USER_ID];
	}
}
?>